<?php
// .-----------------------------------------------------------------------------------
// | WE TRY THE BEST WAY 杭州博也网络科技有限公司
// |-----------------------------------------------------------------------------------
// | Author: 贝贝 <hebiduhebi@163.com>
// | Copyright (c) 2013-2016, http://www.itboye.com. All Rights Reserved.
// |-----------------------------------------------------------------------------------
namespace Shop\Api;
use Common\Api\Api;
use \Shop\Model\SkuModel;
use Shop\Model\VCategorySkuModel;

class SkuApi extends Api{


    /**
     * 查询，不分页
     */
    const QUERY_NO_PAGING = "Shop/Sku/queryNoPaging";
    /**
     * 添加
     */
    const ADD = "Shop/Sku/add";
    /**
     * 保存
     */
    const SAVE = "Shop/Sku/save";
    /**
     * 保存根据ID主键
     */
    const SAVE_BY_ID = "Shop/Sku/saveByID";

    /**
     * 删除
     */
    const DELETE = "Shop/Sku/delete";

    /**
     * 查询
     */
    const QUERY = "Shop/Sku/query";
    /**
     * 查询一条数据
     */
    const GET_INFO = "Shop/Sku/getInfo";
    /**
     * 查询sku以及其属性
     */
    const QUERY_SKU_TABLE = "Shop/Sku/querySkuTable";

	/**
	 * 数量查询
	 */
	const COUNT = "Shop/Sku/count";

	protected function _init(){
		$this->model = new SkuModel();
	}

	public function deleteLangs($id){
        $model = M();
        $model->startTrans();
        $error =  false;
        $skuApi = new SkuApi();
        $skuLangApi = new SkuLangApi();
        $result = $skuLangApi->delete(['sku_id'=>$id]);

        if(!$result['status']){
            $error = $result['info'];
        }
        if($error === false){
            $result = $skuApi->delete(['id'=>$id]);
        }

        if(!$result['status']){
            $error = $result['info'];
        }

        if($error === false){
            $model->commit();
            return $this->apiReturnSuc('操作成功');
        }else{
            $model->rollback();
            return $this->apiReturnSuc('操作失败');
        }
    }

	public function updateLang($id,$sku,$langs,$langs_value){
        $model = M();
        $model->startTrans();
        $skuApi = new SkuApi();
        $skuLangApi = new SkuLangApi();
        $result = $skuApi->saveByID($id,$sku);
        $error = false;
        if(!$result['status']){
            $error = $result['info'];
        }

        if($error === false){
            $sku_id = $id;
            if($sku_id > 0){
                $result = $skuLangApi->delete(['sku_id'=>$id]);
                $allEntity = [];
                for($i = 0 ;$i<count($langs);$i++){
                    array_push($allEntity,[
                        'sku_id'   => $sku_id,
                        'name'     => $langs_value[$i],
                        'lang'     => $langs[$i]
                    ]);
                }
                if(count($allEntity) > 0 ){
                    $result = $skuLangApi->addAll($allEntity);
                }
            }
        }

        if(!$result['status']){
            $error = $result['info'];
        }

        if($error === false){
            $model->commit();
            return $this->apiReturnSuc('操作成功');
        }else{
            $model->rollback();
            return $this->apiReturnSuc('操作失败');
        }
    }


    public function addLang($sku,$langs,$langs_value){
        $model = M();
        $model->startTrans();
        $skuApi = new SkuApi();
        $skuLangApi = new SkuLangApi();
        $result = $skuApi->add($sku);
        $error = false;
        if(!$result['status']){
            $error = $result['info'];
        }

        if($error === false){
            $sku_id = intval($result['info']);
            if($sku_id > 0){
                $allEntity = [];
                for($i = 0 ;$i<count($langs);$i++){
                    array_push($allEntity,[
                        'sku_id'   => $sku_id,
                        'name' => $langs_value[$i],
                        'lang'     => $langs[$i]
                    ]);
                }
                if(count($allEntity) > 0 ){
                    $result = $skuLangApi->addAll($allEntity);
                }
            }
        }

        if(!$result['status']){
            $error = $result['info'];
        }

        if($error === false){
            $model->commit();
            return $this->apiReturnSuc('操作成功');
        }else{
            $model->rollback();
            return $this->apiReturnSuc('操作失败');
        }

    }

    /**
     *
     * @param $lang
     * @param null $map
     * @param array $page
     * @param bool $order
     * @param bool $params
     * @param bool $fields
     * @return array
     */
	public function queryWithLangs($lang,$map = null, $page = array('curpage'=>0,'size'=>10), $order = false, $params = false, $fields = false){
        $query = $this->model;
        $query->alias("sku");

        if(!is_null($map)){
            $query = $query->where($map);
        }
        if(!($order === false)){
            $query = $query->order($order);
        }

        $query = $query->field("sku.name,sku.id");

        $list = $query -> page($page['curpage'] . ',' . $page['size']) -> select();
        $sku_ids = "";
        foreach ($list as $item){
            $sku_ids .= $item['id'].',';
        }

        $result = (new SkuLangApi())->queryNoPaging(['lang'=>$lang,'sku_id'=>['in',$sku_ids]]);

        if($result['status']){
            foreach ($list as &$item) {
                foreach ($result['info'] as $vo) {
                    $item['_lang_name'] = $item['name'];
                    $item['_lang'] = '';
                    if($vo['sku_id'] == $item['id']){
                        $item['_lang_name'] = $vo['name'];
                        $item['_lang'] = $vo['lang'];
                        break;
                    }
                }
            }
        }


        if ($list === false) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }
        $query = $this->model;
        $query->alias("sku");//->join(' itboye_sku_lang as sl ON sl.sku_id = sku.id');
        $count = $query -> where($map) -> count();

        // 查询满足要求的总记录数
        $Page = new \Think\Page($count, $page['size']);

        //分页跳转的时候保证查询条件
        if ($params !== false) {
            foreach ($params as $key => $val) {
                $Page -> parameter[$key] = urlencode($val);
            }
        }

        // 实例化分页类 传入总记录数和每页显示的记录数
        $show = $Page -> show();

        return $this -> apiReturnSuc(array("show" => $show, "list" => $list));

    }

	
	public function querySkuTable($cate_id){
		
		$result = (new VCategorySkuModel())->where(array('cate_id'=>$cate_id));
        $result = $result->order("sort desc") ->select();
		
		if($result === false){
			return $this->apiReturnErr($this->model->getError());
		}

		$skuvalueApi = new SkuvalueApi();
		$return = array();
		foreach($result as $sku){
			$one = array(
				'id'=>$sku['sku_id'],
				'name'=>$sku['name'],
				'value_list'=>array()
			);
			$map = array('sku_id'=>$one['id']);
			$skuvalue = $skuvalueApi->queryNoPaging($map);
			if($skuvalue['status']){
				$one['value_list'] = $skuvalue['info'];
			}else{
				return $this->apiReturnErr($skuvalue['info']);
			}
			array_push($return,$one);
		}
		
		return $this->apiReturnSuc($return);
		
	}
	
}

